package com.dq.rbac.utils;

import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {
    private static final String signingKey = "Dq333-asda7657asdxcvh46";
    private static final long EXPIRE = 60 * 1000; //过期时间

    public static String createToken(String id) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", id);
        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, signingKey) // 签发算法，秘钥为jwtToken
                .setClaims(claims) // body数据，要唯一，自行设置
                .setIssuedAt(new Date(System.currentTimeMillis())) // 设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));// 一天的有效时间
        String token = jwtBuilder.compact();
        return token;
    }

    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(signingKey).parse(token);
            //获取载荷 中的数据
            return (Map<String, Object>) parse.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Claims getClaim(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(signingKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return claims;
    }

    public static Date getExpiration(String token) {
        return getClaim(token).getExpiration();
    }

    public static boolean isExpired(String token) {
        try {
            final Date expiration = getExpiration(token);
            return expiration.before(new Date());
        } catch (ExpiredJwtException expiredJwtException) {
            return true;
        }
    }

    public static void main(String[] args) {
        String token = JWTUtils.createToken("123456");
        System.out.println(token);
        Map<String, Object> map = JWTUtils.checkToken("eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEyMzQ1NiIsImV4cCI6MTY3MjkzNDE5NiwiaWF0IjoxNjcyMDQ1MTY0fQ.1Wbwz8laZ0eHS7SIejDBp0SoIONZA7MoiZz_0A659uM");
        System.out.println(map); //{id=123456, exp=1672934196, iat=1672045164}
        boolean expired = isExpired(token);
        System.out.println("expired = " + expired);
    }
}